import React, { FC, useState, useEffect } from 'react'
import { Pagination } from 'antd'
import { useSearchParams, useLocation, useNavigate } from 'react-router-dom'
import { LIST_PAGE_SIZE, SEARCH_PAGE_SIZE_PARAMS_KEY, SEARCH_PAGE_PARAMS_KEY } from '../../constant'

type pageProps = {
    total: number
}
const ListPage: FC<pageProps> = (props: pageProps) => {
    const { total } = props
    const nav = useNavigate()
    const { pathname } = useLocation()
    const [searchParams] = useSearchParams()
    const [page, setPage] = useState(1)
    const [pageSize, setPageSize] = useState(LIST_PAGE_SIZE)

    // 对url 参数进行监听
    useEffect(() => {
        const pageSize = parseInt(searchParams.get(SEARCH_PAGE_SIZE_PARAMS_KEY) || '') || LIST_PAGE_SIZE
        setPageSize(pageSize)
        const page = parseInt(searchParams.get(SEARCH_PAGE_PARAMS_KEY) || '') || 1
        setPage(page)
    }, [searchParams])
    // 分页change事件
    const pageChangeHandle = (page: number, pageSize: number) => {
        searchParams.set(SEARCH_PAGE_PARAMS_KEY, page.toString())
        searchParams.set(SEARCH_PAGE_SIZE_PARAMS_KEY, pageSize.toString())
        nav({
            pathname,
            search: searchParams.toString()
        })
    }
    return <>
        <Pagination current={page} total={total} pageSize={pageSize} onChange={pageChangeHandle} />
    </>
}

export default ListPage